<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.categoryKey"
        placeholder="请选择分类"
        clearable
        class="filter-item"
        style="width: 200px"
        @change="handleCategoryChange"
      >
        <el-option
          v-for="item in categoryOptions"
          :key="item.categoryKey"
          :label="item.categoryName"
          :value="item.categoryKey"
        />
      </el-select>
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入关键字"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button class="filter-item" type="primary" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="应用Key">
        <template #default="scope">
          {{ scope.row.appKey }}
        </template>
      </el-table-column>
      <el-table-column label="应用名称">
        <template #default="scope">
          {{ scope.row.appName }}
        </template>
      </el-table-column>
      <el-table-column label="应用图标" width="100" align="center">
        <template #default="scope">
          <el-image
            v-if="scope.row.appIcon"
            :src="scope.row.appIcon"
            style="width: 40px; height: 40px"
          />
          <span v-else>无图标</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" width="100" align="center">
        <template #default="scope">
          {{ scope.row.version }}
        </template>
      </el-table-column>
      <el-table-column label="费用" width="80" align="center">
        <template #default="scope">
          {{ scope.row.cost || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status === 'active' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="success"
            @click="handleDownloadFromList(scope.row)"
            v-if="scope.row.appFileKey"
          >
            下载
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :current-page="listQuery.current"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogStatus === 'create' ? '新增应用' : '编辑应用'"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="分类" prop="categoryKey">
          <el-select v-model="temp.categoryKey" class="filter-item" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryKey"
              :label="item.categoryName"
              :value="item.categoryKey"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用Key" prop="appKey">
          <el-input v-model="temp.appKey" />
        </el-form-item>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="temp.appName" />
        </el-form-item>
        <el-form-item label="应用图标" prop="appIcon">
          <el-input v-model="temp.appIcon" placeholder="请输入图标URL" />
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="temp.version" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" type="textarea" />
        </el-form-item>
        <el-form-item label="安装包" prop="appFileKey">
          <div class="file-upload-container">
            <el-upload
              class="upload-demo"
              :action="null"
              :http-request="handleFileUpload"
              :show-file-list="false"
              :before-upload="beforeFileUpload"
            >
              <el-button type="primary">{{ temp.appFileKey ? '更换文件' : '选择文件' }}</el-button>
            </el-upload>
            <div v-if="temp.appFileKey" class="selected-file">
              <span>已选择文件: {{ selectedFileName }}</span>
              <div class="file-actions">
                <el-button type="text" @click="handleDownloadFile" v-if="selectedFileId">下载</el-button>
                <el-button type="text" @click="clearSelectedFile">清除</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="费用" prop="cost">
          <el-input-number v-model="temp.cost" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getAppInfoPage,
  addAppInfo,
  updateAppInfo,
  deleteAppInfo
} from '@/api/appInfo';
import { getCategoryList } from '@/api/category';
import { uploadFile, downloadFile, getFileById, getFilePage } from '@/api/file';

// 数据列表
const list = ref([]);
const total = ref(0);
const listLoading = ref(true);
const dialogFormVisible = ref(false);
const dialogStatus = ref('');
const dataForm = ref(null);
const categoryOptions = ref([]);

// 查询参数
const listQuery = reactive({
  current: 1,
  size: 10,
  keyword: '',
  categoryKey: ''
});

// 表单数据
const temp = reactive({
  id: undefined,
  categoryKey: '',
  appKey: '',
  appName: '',
  appIcon: '',
  version: '',
  description: '',
  appFileKey: '',
  cost: 0,
  status: 'active',
  remark: ''
});

// 表单验证规则
const rules = {
  categoryKey: [{ required: true, message: '请选择分类', trigger: 'change' }],
  appKey: [{ required: true, message: '请输入应用Key', trigger: 'blur' }],
  appName: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  appFileKey: [{ required: true, message: '请上传应用安装包', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取分类列表
const getCategoryOptions = () => {
  getCategoryList().then(response => {
    categoryOptions.value = response.data;
  });
};

// 获取数据列表
const getList = () => {
  listLoading.value = true;
  getAppInfoPage(listQuery)
    .then(response => {
      list.value = response.data.records;
      total.value = response.data.total;
      listLoading.value = false;
    })
    .catch(() => {
      listLoading.value = false;
    });
};

// 分类变更
const handleCategoryChange = () => {
  listQuery.current = 1;
  getList();
};

// 搜索
const handleFilter = () => {
  listQuery.current = 1;
  getList();
};

// 改变每页数量
const handleSizeChange = (val) => {
  listQuery.size = val;
  getList();
};

// 改变页码
const handleCurrentChange = (val) => {
  listQuery.current = val;
  getList();
};

// 重置表单
const resetTemp = () => {
  Object.assign(temp, {
    id: undefined,
    categoryKey: '',
    appKey: '',
    appName: '',
    appIcon: '',
    version: '',
    description: '',
    appFileKey: '',
    cost: 0,
    status: 'active',
    remark: ''
  });
};

// 新增
const handleCreate = () => {
  resetTemp();
  dialogStatus.value = 'create';
  dialogFormVisible.value = true;
  setTimeout(() => {
    if (dataForm.value) {
      dataForm.value.resetFields();
    }
  }, 0);
};

// 创建数据
const createData = () => {
  if (dataForm.value) {
    dataForm.value.validate((valid) => {
      if (valid) {
        addAppInfo(temp).then(() => {
          dialogFormVisible.value = false;
          ElMessage({
            message: '创建成功',
            type: 'success'
          });
          getList();
        });
      }
    });
  }
};

// 编辑
const handleUpdate = (row) => {
  Object.assign(temp, row);
  
  // 重置文件相关变量
  selectedFileName.value = '';
  selectedFileId.value = null;
  
  // 如果有文件标识，获取文件信息
  if (temp.appFileKey) {
    // 查询文件信息
    getFilePage({
      current: 1,
      size: 10,
      keyword: temp.appFileKey
    }).then(response => {
      if (response.data.records && response.data.records.length > 0) {
        // 查找精确匹配的文件
        const fileInfo = response.data.records.find(file => file.fileKey === temp.appFileKey);
        if (fileInfo) {
          selectedFileName.value = fileInfo.fileName;
          selectedFileId.value = fileInfo.id;
        } else if (response.data.records.length > 0) {
          // 如果没有精确匹配，使用第一个结果
          selectedFileName.value = response.data.records[0].fileName;
          selectedFileId.value = response.data.records[0].id;
        }
      } else {
        // 如果没有找到文件，显示提示
        ElMessage.warning('未找到对应的文件信息，可能已被删除');
      }
    }).catch(error => {
      console.error('获取文件信息失败:', error);
      ElMessage.error('获取文件信息失败');
    });
  }
  
  dialogStatus.value = 'update';
  dialogFormVisible.value = true;
};

// 更新数据
const updateData = () => {
  if (dataForm.value) {
    dataForm.value.validate((valid) => {
      if (valid) {
        updateAppInfo(temp).then(() => {
          dialogFormVisible.value = false;
          ElMessage({
            message: '更新成功',
            type: 'success'
          });
          getList();
        });
      }
    });
  }
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteAppInfo(row.id).then(() => {
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
      getList();
    });
  }).catch(() => {
    // 取消删除
  });
};

// Add file upload related variables
const selectedFileName = ref('');
const selectedFileId = ref(null);

// Add file upload related methods
const beforeFileUpload = (file) => {
  const isLt100M = file.size / 1024 / 1024 < 100;
  
  if (!isLt100M) {
    ElMessage.error('文件大小不能超过100MB!');
    return false;
  }
  
  return true;
};

const handleFileUpload = (options) => {
  const { file } = options;
  
  // 创建表单数据
  const formData = new FormData();
  formData.append('file', file);
  formData.append('remark', `应用安装包 - ${temp.appName || '新应用'}`);
  
  // 上传文件
  uploadFile(formData).then(response => {
    ElMessage({
      message: '文件上传成功',
      type: 'success'
    });
    
    // 保存文件标识
    temp.appFileKey = response.data.fileKey;
    selectedFileName.value = response.data.fileName;
    selectedFileId.value = response.data.id;
  }).catch(error => {
    ElMessage.error('文件上传失败: ' + error.message);
  });
};

const handleDownloadFile = () => {
  if (selectedFileId.value) {
    ElMessage({
      message: '正在准备下载...',
      type: 'info'
    });
    
    downloadFile(selectedFileId.value).then(response => {
      // 创建Blob对象
      const blob = new Blob([response.data]);
      
      // 创建下载链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = selectedFileName.value;
      link.click();
      
      // 释放URL对象
      URL.revokeObjectURL(link.href);
      
      ElMessage({
        message: '下载已开始',
        type: 'success'
      });
    }).catch(error => {
      ElMessage.error('下载失败: ' + (error.message || '未知错误'));
    });
  } else {
    ElMessage.warning('无法下载，文件ID不存在');
  }
};

// Add a method to clear the selected file
const clearSelectedFile = () => {
  temp.appFileKey = '';
  selectedFileName.value = '';
  selectedFileId.value = null;
  ElMessage({
    message: '已清除选择的文件',
    type: 'info'
  });
};

// Add a method to download the app from the list
const handleDownloadFromList = (row) => {
  if (!row.appFileKey) {
    ElMessage.warning('该应用没有关联文件');
    return;
  }
  
  // 查询文件信息
  getFilePage({
    current: 1,
    size: 10,
    keyword: row.appFileKey
  }).then(response => {
    if (response.data.records && response.data.records.length > 0) {
      // 查找精确匹配的文件
      const fileInfo = response.data.records.find(file => file.fileKey === row.appFileKey);
      if (fileInfo) {
        // 下载文件
        ElMessage({
          message: '正在准备下载...',
          type: 'info'
        });
        
        downloadFile(fileInfo.id).then(response => {
          // 创建Blob对象
          const blob = new Blob([response.data]);
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = fileInfo.fileName;
          link.click();
          
          // 释放URL对象
          URL.revokeObjectURL(link.href);
          
          ElMessage({
            message: '下载已开始',
            type: 'success'
          });
        }).catch(error => {
          ElMessage.error('下载失败: ' + (error.message || '未知错误'));
        });
      } else {
        ElMessage.warning('未找到对应的文件信息');
      }
    } else {
      ElMessage.warning('未找到对应的文件信息');
    }
  }).catch(error => {
    console.error('获取文件信息失败:', error);
    ElMessage.error('获取文件信息失败');
  });
};

// 页面加载时获取数据
onMounted(() => {
  getCategoryOptions();
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
.file-upload-container {
  display: flex;
  flex-direction: column;
}
.selected-file {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.file-actions {
  display: flex;
  gap: 10px;
}
</style> 